{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "is_executing": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: openai==1.82.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (1.82.0)\n",
      "Requirement already satisfied: requests==2.32.3 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (2.32.3)\n",
      "Requirement already satisfied: tqdm==4.67.1 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (4.67.1)\n",
      "Requirement already satisfied: torch in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (2.2.2)\n",
      "Requirement already satisfied: pymilvus[model] in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (2.6.0)\n",
      "Requirement already satisfied: anyio<5,>=3.5.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from openai==1.82.0) (4.6.2)\n",
      "Requirement already satisfied: distro<2,>=1.7.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from openai==1.82.0) (1.9.0)\n",
      "Requirement already satisfied: httpx<1,>=0.23.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from openai==1.82.0) (0.27.0)\n",
      "Requirement already satisfied: jiter<1,>=0.4.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from openai==1.82.0) (0.9.0)\n",
      "Requirement already satisfied: pydantic<3,>=1.9.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from openai==1.82.0) (2.9.2)\n",
      "Requirement already satisfied: sniffio in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from openai==1.82.0) (1.3.0)\n",
      "Requirement already satisfied: typing-extensions<5,>=4.11 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from openai==1.82.0) (4.12.2)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from requests==2.32.3) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from requests==2.32.3) (3.7)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from requests==2.32.3) (2.3.0)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from requests==2.32.3) (2025.1.31)\n",
      "Requirement already satisfied: setuptools>69 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus[model]) (75.8.0)\n",
      "Requirement already satisfied: grpcio!=1.68.0,!=1.68.1,!=1.69.0,!=1.70.0,!=1.70.1,!=1.71.0,!=1.72.1,!=1.73.0,>=1.66.2 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus[model]) (1.74.0)\n",
      "Requirement already satisfied: protobuf>=5.27.2 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus[model]) (5.29.3)\n",
      "Requirement already satisfied: python-dotenv<2.0.0,>=1.0.1 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus[model]) (1.0.1)\n",
      "Requirement already satisfied: ujson>=2.0.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus[model]) (5.10.0)\n",
      "Requirement already satisfied: pandas>=1.2.4 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus[model]) (2.2.3)\n",
      "Requirement already satisfied: milvus-lite>=2.4.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus[model]) (2.5.1)\n",
      "Requirement already satisfied: pymilvus.model>=0.3.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus[model]) (0.3.2)\n",
      "Requirement already satisfied: filelock in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from torch) (3.17.0)\n",
      "Requirement already satisfied: sympy in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from torch) (1.13.3)\n",
      "Requirement already satisfied: networkx in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from torch) (3.5)\n",
      "Requirement already satisfied: jinja2 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from torch) (3.1.6)\n",
      "Requirement already satisfied: fsspec in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from torch) (2025.3.0)\n",
      "Requirement already satisfied: httpcore==1.* in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from httpx<1,>=0.23.0->openai==1.82.0) (1.0.2)\n",
      "Requirement already satisfied: h11<0.15,>=0.13 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai==1.82.0) (0.14.0)\n",
      "Requirement already satisfied: numpy>=1.23.2 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pandas>=1.2.4->pymilvus[model]) (1.26.4)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pandas>=1.2.4->pymilvus[model]) (2.8.2)\n",
      "Requirement already satisfied: pytz>=2020.1 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pandas>=1.2.4->pymilvus[model]) (2025.1)\n",
      "Requirement already satisfied: tzdata>=2022.7 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pandas>=1.2.4->pymilvus[model]) (2025.1)\n",
      "Requirement already satisfied: annotated-types>=0.6.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pydantic<3,>=1.9.0->openai==1.82.0) (0.7.0)\n",
      "Requirement already satisfied: pydantic-core==2.23.4 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pydantic<3,>=1.9.0->openai==1.82.0) (2.23.4)\n",
      "Requirement already satisfied: transformers>=4.36.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus.model>=0.3.0->pymilvus[model]) (4.55.0)\n",
      "Requirement already satisfied: onnxruntime in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus.model>=0.3.0->pymilvus[model]) (1.21.0)\n",
      "Requirement already satisfied: scipy>=1.10.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from pymilvus.model>=0.3.0->pymilvus[model]) (1.15.2)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from jinja2->torch) (2.1.5)\n",
      "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from sympy->torch) (1.3.0)\n",
      "Requirement already satisfied: six>=1.5 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from python-dateutil>=2.8.2->pandas>=1.2.4->pymilvus[model]) (1.16.0)\n",
      "Requirement already satisfied: huggingface-hub<1.0,>=0.34.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from transformers>=4.36.0->pymilvus.model>=0.3.0->pymilvus[model]) (0.34.4)\n",
      "Requirement already satisfied: packaging>=20.0 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from transformers>=4.36.0->pymilvus.model>=0.3.0->pymilvus[model]) (24.2)\n",
      "Requirement already satisfied: pyyaml>=5.1 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from transformers>=4.36.0->pymilvus.model>=0.3.0->pymilvus[model]) (6.0.2)\n",
      "Requirement already satisfied: regex!=2019.12.17 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from transformers>=4.36.0->pymilvus.model>=0.3.0->pymilvus[model]) (2024.11.6)\n",
      "Requirement already satisfied: tokenizers<0.22,>=0.21 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from transformers>=4.36.0->pymilvus.model>=0.3.0->pymilvus[model]) (0.21.1)\n",
      "Requirement already satisfied: safetensors>=0.4.3 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from transformers>=4.36.0->pymilvus.model>=0.3.0->pymilvus[model]) (0.6.2)\n",
      "Requirement already satisfied: coloredlogs in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from onnxruntime->pymilvus.model>=0.3.0->pymilvus[model]) (15.0.1)\n",
      "Requirement already satisfied: flatbuffers in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from onnxruntime->pymilvus.model>=0.3.0->pymilvus[model]) (25.2.10)\n",
      "Requirement already satisfied: hf-xet<2.0.0,>=1.1.3 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from huggingface-hub<1.0,>=0.34.0->transformers>=4.36.0->pymilvus.model>=0.3.0->pymilvus[model]) (1.1.7)\n",
      "Requirement already satisfied: humanfriendly>=9.1 in /Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages (from coloredlogs->onnxruntime->pymilvus.model>=0.3.0->pymilvus[model]) (10.0)\n"
     ]
    }
   ],
   "source": [
    "!pip install \"pymilvus[model]\" openai==1.82.0 requests==2.32.3 tqdm==4.67.1 torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1ca190681f178fe",
   "metadata": {
    "is_executing": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from openai import OpenAI\n",
    "\n",
    "# 从环境变量获取 DeepSeek API Key\n",
    "# api_key = os.getenv(\"DEEPSEEK_API_KEY\")\n",
    "\n",
    "# 国内代理方式\n",
    "client = OpenAI(\n",
    "    api_key = \"sk-y7DHfp9fzuCxOVm2158638099f9541D3833aB4F4Ed674aCf\",\n",
    "    base_url = \"https://vip.apiyi.com/v1\"    # 此处代理方式，如果是OpenAI官方接口需调整接口地址\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "eaa4047b6c54db43",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-09T07:55:24.459110Z",
     "start_time": "2025-08-09T07:55:24.450179Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "72"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from glob import glob\n",
    "\n",
    "text_lines = []\n",
    "for file in glob(\"milvus_docs/en/faq/*.md\",recursive=True):\n",
    "    with open(file, \"r\", encoding=\"utf-8\") as f:\n",
    "        file_text = f.read()\n",
    "\n",
    "    text_lines += file_text.split(\"# \")\n",
    "\n",
    "len(text_lines)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "2a188fea110a5dde",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-09T08:01:32.595099Z",
     "start_time": "2025-08-09T07:56:52.302953Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/xuyang/miniconda3/envs/langChain/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "from pymilvus import model as milvus_model\n",
    "\n",
    "embedding_model = milvus_model.DefaultEmbeddingFunction()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "1e2897d02e7b32b4",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-09T08:38:06.399538Z",
     "start_time": "2025-08-09T08:38:06.224522Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "768\n",
      "[-0.04836059  0.07163021 -0.01130063 -0.03789341 -0.03320651 -0.01318453\n",
      " -0.03041721 -0.02269495 -0.02317858 -0.00426026]\n"
     ]
    }
   ],
   "source": [
    "test_embedding = embedding_model.encode_queries([\"This is a test\"])[0]\n",
    "embedding_dim = len(test_embedding)\n",
    "print(embedding_dim)\n",
    "print(test_embedding[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "6637f83a832a1224",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-09T08:10:14.314352Z",
     "start_time": "2025-08-09T08:10:14.139894Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-0.02752976  0.0608853   0.00388525 -0.00215193 -0.02774976 -0.0118618\n",
      " -0.04020916 -0.06023417 -0.03813156  0.0100272 ]\n"
     ]
    }
   ],
   "source": [
    "test_embedding_0 = embedding_model.encode_queries([\"That is a test\"])[0]\n",
    "print(test_embedding_0[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3efc6d902f0a0af",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-09T16:43:52.331188Z",
     "start_time": "2025-08-09T16:43:52.291459Z"
    }
   },
   "outputs": [],
   "source": [
    "# 创建 Milvus 客户端\n",
    "\n",
    "from pymilvus import MilvusClient\n",
    "\n",
    "milvus_client = MilvusClient(uri=\"./milvus_demo.db\")\n",
    "\n",
    "collection_name = \"my_rag_collection\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "47f538e3dd851efe",
   "metadata": {},
   "outputs": [],
   "source": [
    "if milvus_client.has_collection(collection_name):\n",
    "    milvus_client.drop_collection(collection_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "ba49a8d39408002d",
   "metadata": {},
   "outputs": [],
   "source": [
    "milvus_client.create_collection(\n",
    "    collection_name=collection_name,\n",
    "    dimension=embedding_dim,\n",
    "    metric_type=\"IP\",  # 内积距离\n",
    "    consistency_level=\"Strong\",  # 支持的值为 (`\"Strong\"`, `\"Session\"`, `\"Bounded\"`, `\"Eventually\"`)。更多详情请参见 https://milvus.io/docs/consistency.md#Consistency-Level。\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "cb6071b1-3b62-4c85-bafe-9862261599e6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "72\n"
     ]
    }
   ],
   "source": [
    "print(len(text_lines))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "a8a104a7939258ad",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
      "To disable this warning, you can either:\n",
      "\t- Avoid using `tokenizers` before the fork if possible\n",
      "TOKENIZERS_PARALLELISM=(true | false)iable \n",
      "Creating embeddings: 100%|██████████| 72/72 [00:00<00:00, 59155.71it/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'insert_count': 72, 'ids': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71], 'cost': 0}"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "\n",
    "data = []\n",
    "\n",
    "doc_embeddings = embedding_model.encode_documents(text_lines)\n",
    "\n",
    "for i, line in enumerate(tqdm(text_lines, desc=\"Creating embeddings\")):\n",
    "    data.append({\"id\": i, \"vector\": doc_embeddings[i], \"text\": line})\n",
    "\n",
    "milvus_client.insert(collection_name=collection_name, data=data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "8c75c1b07a6ff3ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "question = \"How is data stored in milvus?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "49a966339b6f4904",
   "metadata": {},
   "outputs": [],
   "source": [
    "search_res = milvus_client.search(\n",
    "    collection_name=collection_name,\n",
    "    data=embedding_model.encode_queries(\n",
    "        [question]\n",
    "    ),  # 将问题转换为嵌入向量\n",
    "    limit=3,  # 返回前3个结果\n",
    "    search_params={\"metric_type\": \"IP\", \"params\": {}},  # 内积距离\n",
    "    output_fields=[\"text\"],  # 返回 text 字段\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "9603f3ba66a9b63c",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[\n",
      "    [\n",
      "        \" Where does Milvus store data?\\n\\nMilvus deals with two types of data, inserted data and metadata. \\n\\nInserted data, including vector data, scalar data, and collection-specific schema, are stored in persistent storage as incremental log. Milvus supports multiple object storage backends, including [MinIO](https://min.io/), [AWS S3](https://aws.amazon.com/s3/?nc1=h_ls), [Google Cloud Storage](https://cloud.google.com/storage?hl=en#object-storage-for-companies-of-all-sizes) (GCS), [Azure Blob Storage](https://azure.microsoft.com/en-us/products/storage/blobs), [Alibaba Cloud OSS](https://www.alibabacloud.com/product/object-storage-service), and [Tencent Cloud Object Storage](https://www.tencentcloud.com/products/cos) (COS).\\n\\nMetadata are generated within Milvus. Each Milvus module has its own metadata that are stored in etcd.\\n\\n###\",\n",
      "        0.65726637840271\n",
      "    ],\n",
      "    [\n",
      "        \"How does Milvus flush data?\\n\\nMilvus returns success when inserted data are loaded to the message queue. However, the data are not yet flushed to the disk. Then Milvus' data node writes the data in the message queue to persistent storage as incremental logs. If `flush()` is called, the data node is forced to write all data in the message queue to persistent storage immediately.\\n\\n###\",\n",
      "        0.6312143802642822\n",
      "    ],\n",
      "    [\n",
      "        \"How does Milvus handle vector data types and precision?\\n\\nMilvus supports Binary, Float32, Float16, and BFloat16 vector types.\\n\\n- Binary vectors: Store binary data as sequences of 0s and 1s, used in image processing and information retrieval.\\n- Float32 vectors: Default storage with a precision of about 7 decimal digits. Even Float64 values are stored with Float32 precision, leading to potential precision loss upon retrieval.\\n- Float16 and BFloat16 vectors: Offer reduced precision and memory usage. Float16 is suitable for applications with limited bandwidth and storage, while BFloat16 balances range and efficiency, commonly used in deep learning to reduce computational requirements without significantly impacting accuracy.\\n\\n###\",\n",
      "        0.6115782260894775\n",
      "    ]\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "retrieved_lines_with_distances = [\n",
    "    (res[\"entity\"][\"text\"], res[\"distance\"]) for res in search_res[0]\n",
    "]\n",
    "print(json.dumps(retrieved_lines_with_distances, indent=4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "e8950ba06d03bfea",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Where does Milvus store data?\n",
      "\n",
      "Milvus deals with two types of data, inserted data and metadata. \n",
      "\n",
      "Inserted data, including vector data, scalar data, and collection-specific schema, are stored in persistent storage as incremental log. Milvus supports multiple object storage backends, including [MinIO](https://min.io/), [AWS S3](https://aws.amazon.com/s3/?nc1=h_ls), [Google Cloud Storage](https://cloud.google.com/storage?hl=en#object-storage-for-companies-of-all-sizes) (GCS), [Azure Blob Storage](https://azure.microsoft.com/en-us/products/storage/blobs), [Alibaba Cloud OSS](https://www.alibabacloud.com/product/object-storage-service), and [Tencent Cloud Object Storage](https://www.tencentcloud.com/products/cos) (COS).\n",
      "\n",
      "Metadata are generated within Milvus. Each Milvus module has its own metadata that are stored in etcd.\n",
      "\n",
      "###\n",
      "How does Milvus flush data?\n",
      "\n",
      "Milvus returns success when inserted data are loaded to the message queue. However, the data are not yet flushed to the disk. Then Milvus' data node writes the data in the message queue to persistent storage as incremental logs. If `flush()` is called, the data node is forced to write all data in the message queue to persistent storage immediately.\n",
      "\n",
      "###\n",
      "How does Milvus handle vector data types and precision?\n",
      "\n",
      "Milvus supports Binary, Float32, Float16, and BFloat16 vector types.\n",
      "\n",
      "- Binary vectors: Store binary data as sequences of 0s and 1s, used in image processing and information retrieval.\n",
      "- Float32 vectors: Default storage with a precision of about 7 decimal digits. Even Float64 values are stored with Float32 precision, leading to potential precision loss upon retrieval.\n",
      "- Float16 and BFloat16 vectors: Offer reduced precision and memory usage. Float16 is suitable for applications with limited bandwidth and storage, while BFloat16 balances range and efficiency, commonly used in deep learning to reduce computational requirements without significantly impacting accuracy.\n",
      "\n",
      "###\n",
      "How is data stored in milvus?\n"
     ]
    }
   ],
   "source": [
    "context = \"\\n\".join(\n",
    "    [line_with_distance[0] for line_with_distance in retrieved_lines_with_distances]\n",
    ")\n",
    "print(context)\n",
    "print(question)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "2690c6149bcac5bb",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "请使用以下用 <context> 标签括起来的信息片段来回答用 <question> 标签括起来的问题。最后追加原始回答的中文翻译，并用 <translated>和</translated> 标签标注。\n",
      "<context>\n",
      " Where does Milvus store data?\n",
      "\n",
      "Milvus deals with two types of data, inserted data and metadata. \n",
      "\n",
      "Inserted data, including vector data, scalar data, and collection-specific schema, are stored in persistent storage as incremental log. Milvus supports multiple object storage backends, including [MinIO](https://min.io/), [AWS S3](https://aws.amazon.com/s3/?nc1=h_ls), [Google Cloud Storage](https://cloud.google.com/storage?hl=en#object-storage-for-companies-of-all-sizes) (GCS), [Azure Blob Storage](https://azure.microsoft.com/en-us/products/storage/blobs), [Alibaba Cloud OSS](https://www.alibabacloud.com/product/object-storage-service), and [Tencent Cloud Object Storage](https://www.tencentcloud.com/products/cos) (COS).\n",
      "\n",
      "Metadata are generated within Milvus. Each Milvus module has its own metadata that are stored in etcd.\n",
      "\n",
      "###\n",
      "How does Milvus flush data?\n",
      "\n",
      "Milvus returns success when inserted data are loaded to the message queue. However, the data are not yet flushed to the disk. Then Milvus' data node writes the data in the message queue to persistent storage as incremental logs. If `flush()` is called, the data node is forced to write all data in the message queue to persistent storage immediately.\n",
      "\n",
      "###\n",
      "How does Milvus handle vector data types and precision?\n",
      "\n",
      "Milvus supports Binary, Float32, Float16, and BFloat16 vector types.\n",
      "\n",
      "- Binary vectors: Store binary data as sequences of 0s and 1s, used in image processing and information retrieval.\n",
      "- Float32 vectors: Default storage with a precision of about 7 decimal digits. Even Float64 values are stored with Float32 precision, leading to potential precision loss upon retrieval.\n",
      "- Float16 and BFloat16 vectors: Offer reduced precision and memory usage. Float16 is suitable for applications with limited bandwidth and storage, while BFloat16 balances range and efficiency, commonly used in deep learning to reduce computational requirements without significantly impacting accuracy.\n",
      "\n",
      "###\n",
      "</context>\n",
      "<question>\n",
      "How is data stored in milvus?\n",
      "</question>\n",
      "<translated>\n",
      "</translated>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "SYSTEM_PROMPT = \"\"\"\n",
    "Human: 你是一个 AI 助手。你能够从提供的上下文段落片段中找到问题的答案。\n",
    "\"\"\"\n",
    "USER_PROMPT = f\"\"\"\n",
    "请使用以下用 <context> 标签括起来的信息片段来回答用 <question> 标签括起来的问题。最后追加原始回答的中文翻译，并用 <translated>和</translated> 标签标注。\n",
    "<context>\n",
    "{context}\n",
    "</context>\n",
    "<question>\n",
    "{question}\n",
    "</question>\n",
    "<translated>\n",
    "</translated>\n",
    "\"\"\"\n",
    "\n",
    "print(USER_PROMPT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "5bc9096beb457430",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Milvus stores data in two main categories: inserted data and metadata.\n",
      "\n",
      "1. **Inserted Data** (including vector data, scalar data, and collection-specific schema) is stored in persistent storage as incremental logs. It supports multiple object storage backends such as MinIO, AWS S3, Google Cloud Storage (GCS), Azure Blob Storage, Alibaba Cloud OSS, and Tencent Cloud Object Storage (COS).\n",
      "\n",
      "2. **Metadata** is generated internally by Milvus and stored in etcd, with each Milvus module maintaining its own metadata.\n",
      "\n",
      "Additionally, Milvus flushes data to disk by first loading inserted data into a message queue (returning success at this stage), then the data node writes the queued data to persistent storage as incremental logs. Calling `flush()` forces immediate writing of all queued data to storage.\n",
      "\n",
      "<translated>\n",
      "Milvus 将数据存储分为两大类：插入数据和元数据。\n",
      "\n",
      "1. **插入数据**（包括向量数据、标量数据和集合特定模式）以增量日志形式存储在持久化存储中。支持多种对象存储后端，如 MinIO、AWS S3、Google Cloud Storage (GCS)、Azure Blob Storage、阿里云OSS和腾讯云对象存储 (COS)。\n",
      "\n",
      "2. **元数据**由 Milvus 内部生成并存储在 etcd 中，每个 Milvus 模块维护各自的元数据。\n",
      "\n",
      "此外，Milvus 通过先将插入数据加载到消息队列（此时返回成功），随后数据节点将队列中的数据作为增量日志写入持久化存储来实现数据刷盘。调用 `flush()` 会强制立即将所有队列中的数据写入存储。\n",
      "</translated>\n"
     ]
    }
   ],
   "source": [
    "response = client.chat.completions.create(\n",
    "    model=\"deepseek-chat\",\n",
    "    messages=[\n",
    "        {\"role\": \"system\", \"content\": SYSTEM_PROMPT},\n",
    "        {\"role\": \"user\", \"content\": USER_PROMPT},\n",
    "    ],\n",
    ")\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7bebcf05-df56-40af-a51d-b9850924569b",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58c1ad85-a4a0-401e-9a74-c2ee01a19f94",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "7d86e24f-2887-4e7d-8c65-3f1670815568",
   "metadata": {},
   "source": [
    "### 民法典练习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "bf1d0cbe-ff3e-428d-9d7e-f1cfefd44d73",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "388"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from glob import glob\n",
    "\n",
    "mfd_lines = []\n",
    "for file in glob(\"milvus_docs/mfd.md\",recursive=True):\n",
    "    with open(file, \"r\", encoding=\"utf-8\") as f:\n",
    "        file_text = f.read()\n",
    "\n",
    "    mfd_lines += file_text.split(\"\\n**\")\n",
    "\n",
    "len(mfd_lines)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "17722e9a-3d45-4c99-88d9-34f14b66e421",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第二百三十三条** 善意取得。\n",
      "无处分权人将不动产或者动产转让给受让人，受让人取得该不动产或者动产时是善意，且该不动产或者动产已经登记或者交付的，受让人取得该不动产或者动产的所有权。\n",
      "受让人依照前款规定取得不动产或者动产的所有权的，原权利人有权向无处分权人请求损害赔偿。\n",
      "当事人善意取得其他物权的，参照适用前两款规定。\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(mfd_lines[30])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "43868620-f0bb-43b2-a172-5dbd22ba3aad",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "768\n",
      "[-0.0315465   0.01001122  0.01007959 -0.0767322   0.02531541  0.02973413\n",
      "  0.01041664 -0.01747014 -0.03290387  0.05578492]\n"
     ]
    }
   ],
   "source": [
    "from pymilvus import model as milvus_model\n",
    "\n",
    "embedding_model = milvus_model.DefaultEmbeddingFunction()\n",
    "embedding_dim = 768\n",
    "\n",
    "# test_embedding = embedding_model.encode_queries([\"民法典RAG\"])[0]\n",
    "# embedding_dim = len(test_embedding)\n",
    "# print(embedding_dim)\n",
    "# print(test_embedding[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "2fea6cbe-0bf6-4162-8ca1-c6f4f8f012f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建 Milvus 客户端\n",
    "\n",
    "from pymilvus import MilvusClient\n",
    "\n",
    "# 创建客户端\n",
    "milvus_client = MilvusClient(uri=\"./milvus_demo.db\")\n",
    "\n",
    "# 指定collection名称\n",
    "collection_name = \"mfd_rag_collection\"\n",
    "\n",
    "# 如果已存在，则删除\n",
    "if milvus_client.has_collection(collection_name):\n",
    "    milvus_client.drop_collection(collection_name)\n",
    "\n",
    "# 创建collection\n",
    "milvus_client.create_collection(\n",
    "    collection_name=collection_name,\n",
    "    dimension=embedding_dim,\n",
    "    metric_type=\"IP\",  # 内积距离\n",
    "    consistency_level=\"Strong\",  # 支持的值为 (`\"Strong\"`, `\"Session\"`, `\"Bounded\"`, `\"Eventually\"`)。更多详情请参见 https://milvus.io/docs/consistency.md#Consistency-Level。\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "id": "e208572a-7fd6-46da-ad8b-324ba48f25af",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Creating embeddings: 100%|██████████| 388/388 [00:00<00:00, 1688163.85it/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'insert_count': 388, 'ids': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387], 'cost': 0}"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "\n",
    "mfd_data = []\n",
    "# embedding\n",
    "mdf_docs_embeddings = embedding_model.encode_documents(mfd_lines)\n",
    "\n",
    "# 拼装向量数据对象\n",
    "for i, line in enumerate(tqdm(mfd_lines, desc=\"Creating embeddings\")):\n",
    "    mfd_data.append({\"id\": i, \"vector\": mdf_docs_embeddings[i], \"text\": line})\n",
    "\n",
    "# 批量写入\n",
    "milvus_client.insert(collection_name=collection_name, data=mfd_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "011d194d-504f-45ab-aac2-3bbb079de8cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 拼装AI大模型Prompt\n",
    "SYSTEM_PROMPT = \"\"\"\n",
    "Human: 你是一个 AI 助手。你能够从提供的上下文段落片段中找到问题的答案。\n",
    "\"\"\"\n",
    "\n",
    "def create_user_prompt(context: str, question: str) -> str:\n",
    "    template = f\"\"\"\n",
    "    请使用以下用 <context> 标签括起来的信息片段来回答用 <question> 标签括起来的问题。并使用通俗易懂的语言，解释其条款内容，并用 <explain>和</explain> 标签标注。\n",
    "    <context>\n",
    "    {context}\n",
    "    </context>\n",
    "    <question>\n",
    "    {question}\n",
    "    </question>\n",
    "    <explain>\n",
    "    </explain>\n",
    "    \"\"\"\n",
    "\n",
    "    # print(template)\n",
    "    \n",
    "    return template\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "id": "a9103604-7d79-4cf7-b5f2-bd3b19bbe393",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 搜索\n",
    "def search_milvus(question: str) -> str: \n",
    "    search_res = milvus_client.search(\n",
    "        collection_name=collection_name,\n",
    "        data=embedding_model.encode_queries(\n",
    "            [question]\n",
    "        ),  # 将问题转换为嵌入向量\n",
    "        limit=3,  # 返回前3个结果\n",
    "        search_params={\"metric_type\": \"IP\", \"params\": {}},  # 内积距离\n",
    "        output_fields=[\"text\"],  # 返回 text 字段\n",
    "    )\n",
    "    retrieved_lines_with_distances = [\n",
    "        (res[\"entity\"][\"text\"], res[\"distance\"]) for res in search_res[0]\n",
    "    ]\n",
    "    return retrieved_lines_with_distances"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "2efca777-0a68-4277-8c4f-9758ea94db1c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "question = \"征收集体土地，是否合理合法，有什么补偿？\"\n",
    "\n",
    "s_res = search_milvus(question)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "id": "3f87456c-6a8e-419b-a41e-608cdea45e04",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('第五百七十六条** 损害赔偿的范围，包括因违约造成的损失，以及合同履行后可以获得的利益；但是，不得超过违约方订立合同时预见到或者应当预见到的因违约可能造成的损失。\\n',\n",
       "  0.7361540198326111),\n",
       " ('第五百一十一条** 合同生效后，当事人就质量、价款或者报酬、履行地点等内容没有约定或者约定不明确的，可以协议补充；不能达成补充协议的，按照合同有关条款或者交易习惯确定。\\n',\n",
       "  0.7361540198326111),\n",
       " ('第四百四十一条** 质权人转让质押财产的，转让所得的价款，应当向质权人提前清偿债务或者提存。\\n转让的价款，应当优先用于清偿质权人所担保的债务。\\n',\n",
       "  0.7296239733695984)]"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s_res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "id": "1cce32cf-9cb3-476e-9a35-ecc1e9f2761d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "    请使用以下用 <context> 标签括起来的信息片段来回答用 <question> 标签括起来的问题。并使用通俗易懂的语言，解释其条款内容，并用 <explain>和</explain> 标签标注。\n",
      "    <context>\n",
      "    第五百七十六条** 损害赔偿的范围，包括因违约造成的损失，以及合同履行后可以获得的利益；但是，不得超过违约方订立合同时预见到或者应当预见到的因违约可能造成的损失。\n",
      "\n",
      "第五百一十一条** 合同生效后，当事人就质量、价款或者报酬、履行地点等内容没有约定或者约定不明确的，可以协议补充；不能达成补充协议的，按照合同有关条款或者交易习惯确定。\n",
      "\n",
      "第四百四十一条** 质权人转让质押财产的，转让所得的价款，应当向质权人提前清偿债务或者提存。\n",
      "转让的价款，应当优先用于清偿质权人所担保的债务。\n",
      "\n",
      "    </context>\n",
      "    <question>\n",
      "    征收集体土地，是否合理合法，有什么补偿？\n",
      "    </question>\n",
      "    <explain>\n",
      "    </explain>\n",
      "    \n"
     ]
    }
   ],
   "source": [
    "context = \"\\n\".join(\n",
    "    [line_with_distance[0] for line_with_distance in s_res]\n",
    ")\n",
    "USER_PROMPT = create_user_prompt(context, question)\n",
    "print(USER_PROMPT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "id": "eb3f2026-030d-44ae-a609-414a97bbb592",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "根据提供的上下文，这些法律条款并未直接涉及集体土地征收的合法性和补偿问题。它们主要规范的是合同违约赔偿（第五百七十六条）、合同内容补充（第五百一十一条）以及质权人处理质押财产（第四百四十一条）的情形。\n",
      "\n",
      "<explain>\n",
      "1. **第五百七十六条**：这条讲的是如果一方违反合同，需要赔偿对方的损失，包括实际损失和合同履行后能得到的利益，但赔偿不能超过违约方在签合同时能预见到的损失范围。  \n",
      "   *比如：甲方违约导致乙方损失10万元，但合同签订时甲方只能预见到5万元的损失，那么最多赔5万。*\n",
      "\n",
      "2. **第五百一十一条**：如果合同里对质量、价格、履行地点等内容没写清楚，双方可以协商补充；协商不成的，就按合同其他条款或行业习惯来定。  \n",
      "   *比如：装修合同没写用什么品牌瓷砖，双方可协商；若协商不成，按当地装修市场标准选择。*\n",
      "\n",
      "3. **第四百四十一条**：如果质押的东西（比如抵押的车）被卖掉，卖的钱要先还债或存起来，优先还质押权人的债务。  \n",
      "   *比如：A用车子抵押借钱，还不上时车子被卖掉，卖车的钱先还A欠的债。*\n",
      "\n",
      "但关于**集体土地征收**的问题，需参考《土地管理法》等专门法规，通常需符合公共利益、经合法程序，并给予合理补偿（如土地补偿费、安置补助费等）。当前提供的条款不直接适用此问题。\n",
      "</explain>\n"
     ]
    }
   ],
   "source": [
    "response = client.chat.completions.create(\n",
    "    model=\"deepseek-chat\",\n",
    "    messages=[\n",
    "        {\"role\": \"system\", \"content\": SYSTEM_PROMPT},\n",
    "        {\"role\": \"user\", \"content\": USER_PROMPT},\n",
    "    ],\n",
    ")\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a4fe736e-d8f2-4e29-9f91-daed4406843e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "id": "7ba29290-56a8-4455-b33f-d3528241946b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "question = \"不动产权利人有什么权利和义务？\"\n",
    "\n",
    "s_res = search_milvus(question)\n",
    "\n",
    "context = \"\\n\".join(\n",
    "    [line_with_distance[0] for line_with_distance in s_res]\n",
    ")\n",
    "USER_PROMPT = create_user_prompt(context, question)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "id": "688e7223-7241-4410-aeaa-fd2b5a6621cd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "根据提供的法律条款，不动产权利人的权利和义务可以总结如下：\n",
      "\n",
      "<explain>\n",
      "1. **查询复制权**：权利人可以申请查询和复制自己不动产的登记资料（依据第218条）。比如房主可以到房管局调取自己房产的档案信息。\n",
      "\n",
      "2. **信息保护权**：权利人的物权受法律平等保护，禁止他人非法侵犯（第207条）。这意味着他人不能随意查询你的房产信息，除非是利害关系人。\n",
      "\n",
      "3. **配合查询义务**：当利害关系人（如买家、抵押权人）依法申请查询时，登记机构必须提供资料（第219条），权利人需接受这种合法的信息查询。\n",
      "\n",
      "简单说，房主有权掌握自己房产的登记信息，同时也要接受法律规定的必要信息披露，但所有物权都受到法律一视同仁的保护。\n",
      "</explain>\n"
     ]
    }
   ],
   "source": [
    "response = client.chat.completions.create(\n",
    "    model=\"deepseek-chat\",\n",
    "    messages=[\n",
    "        {\"role\": \"system\", \"content\": SYSTEM_PROMPT},\n",
    "        {\"role\": \"user\", \"content\": USER_PROMPT},\n",
    "    ],\n",
    ")\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1654aa8f-df85-4bb3-bbcb-148e8c3276b7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:langChain]",
   "language": "python",
   "name": "conda-env-langChain-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
